package com.xiaohudie.JUC;

/**
 * @Author xiao hu die
 * @Date 2022/1/12 22:07
 * @Version 1.0
 */

import lombok.SneakyThrows;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**使用lock操作线程*/
class Share2{
    private Integer a =0;
    /**LOCK需要new出来*/
    private Lock lock2 =new ReentrantLock();
    private Condition condition =lock2.newCondition();

    @SneakyThrows
    public void add(){
      /**上锁*/
      lock2.lock();
      try {
          /**判断*/
          while (a!=0){
              condition.await();
          }
          a++;
          System.out.println(Thread.currentThread().getName()+a);
          condition.signalAll();
      }finally {
          lock2.unlock();
      }
    }
    @SneakyThrows
    public void delete(){
        /**上锁*/
        lock2.lock();
        try {
            /**判断*/
            while (a!=1){
                condition.await();
            }
            a--;
            System.out.println(Thread.currentThread().getName()+a);
            condition.signalAll();
        }finally {
            lock2.unlock();
        }
    }
}
public class ThreadDemo2 {
    public static void main(String[] args) {
        Share2 share2 = new Share2();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                share2.add();
            }
        },"AA").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                share2.delete();
            }
        },"BB").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                share2.add();
            }
        },"CC").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                share2.delete();
            }
        },"DD").start();
    }
}
